from rest_framework.viewsets import GenericViewSet
from utils.common_response import APIResponse
from user.authentication import LoginAuthentication
from .models import Roles, Dept, Job, Menu
from utils.common_pagination import PageNumberPagination
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin, \
    RetrieveModelMixin
from .serializer import RolesSerializer, DeptSerializer, DeptUserSerializer, JobSerializer, MenuSerializer, \
    DeptCreateUpdateRetrieveSerializer, MenuOnlySerializer, MenuPermissionSerializer
from rest_framework.decorators import action


# 角色视图
class PermissionRolesView(GenericViewSet, ListModelMixin, CreateModelMixin, RetrieveModelMixin, DestroyModelMixin,
                          UpdateModelMixin):
    authentication_classes = [LoginAuthentication]
    serializer_class = Roles
    queryset = Roles.objects.all().filter(is_delete=False).order_by('id')
    pagination_class = PageNumberPagination

    def get_serializer_class(self):
        if self.action == 'list':
            return RolesSerializer
        else:
            return RolesSerializer

    def list(self, request):
        res = super().list(request)
        return APIResponse(data=res.data)

    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return APIResponse(data=res.data)

    def create(self, request):
        res = super().create(request)
        return APIResponse(data=res.data)

    def destroy(self, request, *args, **kwargs):
        res = super().destroy(request, *args, **kwargs)
        return APIResponse(data=res.data)

    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        return APIResponse(data=res.data)

    @action(methods=['POST'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        print(request.data.get('ids'))
        self.get_queryset().filter(id__in=request.data.get('ids', [])).delete()
        return APIResponse()


# 部门视图
class PermissionDeptView(GenericViewSet, ListModelMixin, CreateModelMixin, DestroyModelMixin, RetrieveModelMixin,
                         UpdateModelMixin):
    authentication_classes = [LoginAuthentication]
    serializer_class = DeptSerializer
    queryset = Dept.objects.all().filter(is_delete=False, pid=None).order_by('id')
    pagination_class = PageNumberPagination

    def get_serializer_class(self):
        if self.action == 'list':
            return DeptSerializer
        elif self.action == 'user_dept_list':
            return DeptUserSerializer
        elif self.action == 'create':
            return DeptCreateUpdateRetrieveSerializer
        elif self.action == 'retrieve':
            return DeptCreateUpdateRetrieveSerializer
        elif self.action == 'update':
            return DeptCreateUpdateRetrieveSerializer

    # 因为查询只查了父部门，在此重写，给删除使用
    def get_queryset(self):
        if self.action == 'list':
            return super().get_queryset()
        elif self.action == 'user_dept_list':
            return super().get_queryset()
        else:
            return Dept.objects.all().filter(is_delete=False)

    def list(self, request):
        res = super().list(request)
        return APIResponse(data=res.data)

    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return APIResponse(data=res.data)

    def create(self, request):
        res = super().create(request)
        return APIResponse(data=res.data)

    def destroy(self, request, *args, **kwargs):
        res = super().destroy(request, *args, **kwargs)
        return APIResponse(data=res.data)

    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        return APIResponse(data=res.data)

    # 给用户新增页面使用的
    @action(methods=['GET'], detail=False)
    def user_dept_list(self, request):
        res = super().list(request)
        return APIResponse(data=res.data)


# 岗位视图
class PermissionJobView(GenericViewSet, ListModelMixin, CreateModelMixin, DestroyModelMixin, RetrieveModelMixin,
                        UpdateModelMixin):
    authentication_classes = [LoginAuthentication]
    serializer_class = JobSerializer
    queryset = Job.objects.all().filter(is_delete=False).order_by('id')
    pagination_class = PageNumberPagination

    def get_serializer_class(self):
        if self.action == 'list':
            return JobSerializer
        else:
            return JobSerializer

    def list(self, request):
        res = super().list(request)
        return APIResponse(data=res.data)

    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return APIResponse(data=res.data)

    def create(self, request):
        res = super().create(request)
        return APIResponse(data=res.data)

    @action(methods=['POST'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        print(request.data.get('ids'))
        self.get_queryset().filter(id__in=request.data.get('ids', [])).delete()
        return APIResponse()

    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        return APIResponse(data=res.data)


# 菜单视图
class PermissionMenuView(GenericViewSet, ListModelMixin, CreateModelMixin, DestroyModelMixin, RetrieveModelMixin,
                         UpdateModelMixin):
    authentication_classes = [LoginAuthentication]
    serializer_class = MenuSerializer
    queryset = Menu.objects.all().filter(is_delete=False, is_menu=True).order_by('id')

    def get_serializer_class(self):
        if self.action == 'all':
            return MenuSerializer
        elif self.action == 'menu_list':
            return MenuOnlySerializer
        else:
            return MenuSerializer

    def get_queryset(self):
        if self.action == 'all':
            return super().get_queryset()
        elif self.action == 'menu_list':
            return super().get_queryset()
        else:
            return Menu.objects.all().filter(is_delete=False).order_by('id')

    # 获取所有菜单
    @action(methods=['GET'], detail=False)
    def all(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        return APIResponse(data=res.data)

    # 给用户菜单选择使用的
    @action(methods=['GET'], detail=False)
    def menu_list(self, request):
        res = super().list(request)
        return APIResponse(data=res.data)

    # 根据当前用户获取相应权限的菜单 # 首页菜单和权限
    # def list(self, request, *args, **kwargs):
    #     nav = [
    #         {
    #             'name': 'SysManga',
    #             'title': '系统管理',
    #             'icon': 'el-icon-s-operation',
    #             'component': '',
    #             'path': '',
    #             'children': [
    #                 {
    #                     'name': 'SysUser',
    #                     'title': '用户管理',
    #                     'icon': 'el-icon-s-custom',
    #                     'path': '/admin/user',
    #                     'component': 'admin/User',
    #                     'children': []
    #                 },
    #                 {
    #                     'name': 'SysRole',
    #                     'title': '角色管理',
    #                     'icon': 'el-icon-rank',
    #                     'path': '/admin/role',
    #                     'component': 'admin/Role',
    #                     'children': []
    #                 },
    #                 {
    #                     'name': 'SysMenu',
    #                     'title': '菜单管理',
    #                     'icon': 'el-icon-menu',
    #                     'path': '/admin/menu',
    #                     'component': 'admin/Menu',
    #                     'children': []
    #                 },
    #                 {
    #                     'name': 'SysDept',
    #                     'title': '部门管理',
    #                     'icon': 'el-icon-menu',
    #                     'path': '/admin/dept',
    #                     'component': 'admin/Dept',
    #                     'children': []
    #                 },
    #                 {
    #                     'name': 'SysJob',
    #                     'title': '岗位管理',
    #                     'icon': 'el-icon-menu',
    #                     'path': '/admin/job',
    #                     'component': 'admin/Job',
    #                     'children': []
    #                 }
    #             ]
    #         },
    #         {
    #             'name': 'SysTools',
    #             'title': '系统工具',
    #             'icon': 'el-icon-s-tools',
    #             'path': '',
    #             'component': '',
    #             'children': [
    #                 {
    #                     'name': 'SysDict',
    #                     'title': '数字字典',
    #                     'icon': 'el-icon-s-order',
    #                     'path': '/admin/dicts',
    #                     'component': '',
    #                     'children': []
    #                 },
    #             ]
    #         }
    #     ]
    #     authoritys = ['sys:user:list', "sys:user:save", "sys:user:delete"]
    #
    #     return APIResponse(nav=nav, authoritys=authoritys)

    def list(self, request, *args, **kwargs):
        # 如果是超级管理员，拥有所有权限
        if request.user.is_superuser:
            menus = Menu.objects.filter(is_delete=False, is_menu=True).order_by('menu_sort')
            ser = MenuPermissionSerializer(instance=menus, many=True)
            nav = ser.data
            buttons = Menu.objects.filter(type=2)
            authoritys = [item.permission for item in buttons]
        else:
            # 根据当前登录用户，获得所有角色
            roles = request.user.roles.all()
            # 根据角色，取出所有菜单权限,会有重复所有用集合去重
            catalog_ids = []  # 存放所有目录id
            menus_ids = []  # 存放所有菜单id

            buttons = []  # 存放所有按钮
            for role in roles:
                # 根据角色获取所有目录
                catalog_ids += role.menus.filter(type=0).values_list('id', flat=True)
                menus_ids += role.menus.filter(type=1).values_list('id', flat=True)
                # 根据角色获取所有按钮
                buttons += role.menus.filter(type=2)
            # 序列化所有目录及子菜单
            menus_qs = Menu.objects.filter(id__in=list(set(catalog_ids)))
            ser = MenuPermissionSerializer(instance=menus_qs, many=True, context={'menus_ids': list(set(menus_ids))})
            nav = ser.data
            # 通过按钮拿到所有权限放到列表中
            authoritys = [item.permission for item in buttons]
            # 去重
            authoritys = list(set(authoritys))
        return APIResponse(nav=nav, authoritys=authoritys)

    def retrieve(self, request, *args, **kwargs):
        res = super().retrieve(request, *args, **kwargs)
        return APIResponse(data=res.data)

    def create(self, request):
        res = super().create(request)
        return APIResponse(data=res.data)

    def destroy(self, request, *args, **kwargs):
        res = super().destroy(request, *args, **kwargs)
        return APIResponse(data=res.data)

    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        return APIResponse(data=res.data)
